<template>
	<!--  #ifdef MP-WEIXIN -->
	<page-meta :page-style="'overflow:'+(showScreen?'hidden':'visible')"></page-meta>
	<!--  #endif -->

	<view class="content">
		<view :style="{'background' : `linear-gradient(360deg, #FE7E17 0%, #FF2A47 ${headerBgTop}%)`}"
			class="home-header-top u-flex u-flex-items-end " @tap="handleMapLocation()">
			<u-icon name="map" color="#fff" size="40rpx"></u-icon>
			<text class="map-text">{{currentLocation}}</text>
		</view>

		<view class="home-header">
			<view class="header-search" @tap="toSearchShop('')">
				<u-search placeholder="寻找好店" :show-action="false" disabled="false"></u-search>
			</view>
			<view class="header-banner">
				<image class="banner-img" mode="widthFix" :src="getimageUrl('home-banner.png')"></image>
			</view>
		</view>
		<view class="home-class">
			<swiper :indicator-dots="true" class="swiper" indicatorActiveColor="#FF5046">
				<swiper-item>
					<u-grid :border="false" col="5">
						<u-grid-item v-for="item in businessCategory" :key="item.id"
							customStyle="padding-top: 10px; padding-bottom: 10px" @tap="toSearchShop(item.type)">
							<image :src="item.icon" style="width: 60rpx; height: 60rpx;"></image>
							<text class="grid-text">{{item.name}}</text>
						</u-grid-item>
					</u-grid>
				</swiper-item>
			</swiper>
		</view>

		<view class="home-channel">
			<view class="channel-title u-flex u-flex-between u-flex-items-center">
				<text class="channel-title-text">【限时优惠】超值福利等你来领取！</text>
				<view class="channel-title-guide u-flex" @tap="toBbeginnerTutorial">
					<u-icon name="question-circle" color="#fff" size="25rpx"></u-icon>
					<text class="guide-text">新手指引</text>
				</view>
			</view>
			<view class="channel-item u-flex">
				<view class="channel-item-con u-flex">
					<view class="con-main">
						<view class="con-title">商家入驻</view>
						<view class="con-text">
							享受<text class="text-color">销量提升、好</text>
							<view style="position: absolute; width: 160%">
								<text class="text-color">评增加、</text>等多重好处。
							</view>
						</view>
					</view>
					<image style="width: 150rpx; height: 100rpx;" :src="getimageUrl('channel-left.jpg')"></image>
				</view>
				<view class="channel-item-con u-flex">
					<view class="con-main">
						<view class="con-title">粉丝福利群</view>
						<view class="con-r-btn">
							<u-button type="primary" shape="circle" size="mini" text="立即加入" color="#FF5151"
								@tap="handleAdditiveGroup"></u-button>
						</view>
					</view>
					<image style="width: 150rpx; height: 100rpx;" :src="getimageUrl('channel-right.jpg')" mode="">
					</image>
				</view>
			</view>
		</view>

		<u-sticky offset-top="150rpx" customNavHeight="20px" bg-color="#F2F2F2" style="z-index: 200;">
			<view class="screen-cont u-flex u-flex-items-center">
				<view class="u-flex u-flex-items-center">
					<uni-data-checkbox mode="tag" selectedColor="#F9C36C" multiple :localdata="checkboxClassA"
						v-model="checkType" @change="changeScreen">
					</uni-data-checkbox>
					<view class="screen-other-btn u-flex u-flex-items-center"
						:class="(checkPlatform.length ||checkCategory.length) ? 'screen-other-btn-active' : ''"
						@tap="handleShowScreen">
						筛选<u-icon style="margin-left: 5rpx;" size="18rpx"
							:name="showScreen? 'arrow-up-fill' : 'arrow-down-fill'"
							:color="(checkPlatform.length ||checkCategory.length) ? '#fff' : '#333'"></u-icon>
					</view>
				</view>
				<view class="u-flex u-flex-items-center screen-cont-right">
					只看可抢
					<u-switch style="margin-left: 10rpx;" v-model="snatchable" size="20" activeColor="#F9C36C"
						@change="changeScreen"></u-switch>
				</view>
			</view>

			<view class="screen-other-cont" v-if="showScreen">
				<text class="other-cont-title">平台</text>
				<uni-data-checkbox mode="tag" selectedColor="#F9C36C" multiple :localdata="checkboxListPlatform"
					v-model="checkPlatform"></uni-data-checkbox>
				<text class="other-cont-title">品类</text>
				<uni-data-checkbox mode="tag" selectedColor="#F9C36C" multiple :map="{text:'name',value:'type'}"
					:localdata="businessCategory" v-model="checkCategory"></uni-data-checkbox>

				<view class="u-flex other-cont-btn">
					<view class="btn" style="padding-right: 4%;">
						<u-button type="primary" size="small" text="重置" color="#FF5151" plain
							@tap="resettingDetermine"></u-button>
					</view>
					<view class="btn">
						<u-button type="primary" size="small" text="确定" color="#FF5151"
							@tap="screenDetermine"></u-button>
					</view>
				</view>
			</view>
		</u-sticky>

		<!--列表-->
		<view class="shop-list-box">
			<view :class="classListTypeBg(item.platform)" class="details-list u-flex" v-for="item in listData"
				:key="item.id">
				<view class="details-img-con">
					<image class="details-img" :src="item.shopLogo" mode="aspectFill"></image>
				</view>
				<view class="details-item">
					<view class="details-title-text m-b-10">{{item.shopName}}</view>
					<view class="item-content-p-t u-flex m-b-10">
						<view class="price">满{{item.returnThreshold}}返{{item.fullRefund}}</view>
						<view class="time">{{item.startTimeFormat}}-{{item.endTimeFormat}}</view>
					</view>
					<view class="item-content-desc u-flex m-b-10">
						<text class="desc-cont">月售{{item.monthly}}</text>
						<text class="desc-cont">人均{{item.average}}元</text>
						<view class="desc-cont u-flex"><u-icon name="tags"></u-icon> {{item.distance}}km</view>
					</view>
					<view class="item-content-bottom u-flex" @tap="toOrderGrabbing(item)">
						<view class="bottom-item">剩余<text class="num">{{item.surplusQuantity}}</text>份<text
								class="sign">{{item.completeRequire_dictText}}</text></view>
						<view class="bottom-btn">去抢单</view>
					</view>
				</view>
			</view>

			<u-empty marginTop="100rpx" v-if="!listData.length" :icon="getimageUrl('empty-home.png')"></u-empty>
		</view>

		<u-overlay :show="showScreen" zIndex='100'></u-overlay>

		<u-popup :show="popAdditiveGroup" mode="center" @close="popAdditiveGroup=false" :closeable="true">
			<view class="additive-group">
				<view class="additive-group-title">雁塔区粉丝福利群</view>
				<img style="width: 400rpx;height: 400rpx;" :src="xccQrCodeImg" />
				<view class="additive-group-text">扫描二维码入群</view>
			</view>
		</u-popup>

		<view class="wrap">
			<up-back-top :scroll-top="scrollTop" :customStyle="backCustomStyle"></up-back-top>
		</view>

		<!-- 客服 -->
		<button class="fixed_btn btn_style" open-type="contact">
			<image :src="getimageUrl('kefu.png')" class="fixed_btn_img"></image>
		</button>
	</view>
</template>

<script lang="ts" setup>
	import { ref, onMounted, unref, reactive, getCurrentInstance } from "vue";
	import { onPageScroll, onShow, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';
	import { addressResolution } from '@/common/sys.api';
	import { queryUserActivityPage, queryXccQrCode, queryBusinessCategoryList } from '@/common/index.api';
	import { getimageUrl } from '@/util/util.js';
	const { proxy } = getCurrentInstance();

	let headerBgTop = ref(0)
	let scrollTop = ref(0)
	let showScreen = ref(false)
	let popAdditiveGroup = ref(false)
	let currentLocation = ref('获取位置中');
	// 小程序加群二维码
	let xccQrCodeImg = ref('')

	// 返回顶部样式
	let backCustomStyle = ref({
		// with: '580rpx',
		// height: '580rpx',
		backgroundColor: '#fff',
		boxShadow: '0px 10px 15px 0px rgba(153, 153, 153, 0.3)'
	})

	// 列表筛选条件
	let checkType = ref([])
	let checkPlatform = ref([])
	let checkCategory = ref([])
	let snatchable = ref(false)
	let checkboxClassA = [{ value: 'izHighRebate', "text": "高返利" }, { value: 'izFeedback', "text": "无需反馈" }]
	let checkboxListPlatform = [{ value: 'mt', "text": "美团" }, { value: 'elm', "text": "饿了么" }, { value: 'dy', "text": "抖音小店" }]
	let businessCategory = ref([])

	const state = reactive({
		filtrate: {
			pageNo: 1,
			pageSize: 10,
			latitude: 0,
			longitude: 0,
			izFeedback: null,
			izHighRebate: null,
			izSnatchable: null,
			platform: null,
			shopType: null,
		},
		loadStatus: 'loading',  //加载样式：more-加载前样式，loading-加载中样式，nomore-没有数据样式
		isLoadMore: false,  //是否加载中
	})
	let listData = ref([])

	function classListTypeBg(type) {
		var genderMap = {
			'elm': 'list-bgimg-elme',
			'mt': 'list-bgimg-meituan',
			'dy': 'list-bgimg-douyin',
		};
		return genderMap[type]
	}

	function changeScreen() {
		state.filtrate.izFeedback = Number(unref(checkType).includes('izFeedback'))
		state.filtrate.izHighRebate = Number(unref(checkType).includes('izHighRebate'))
		state.filtrate.izSnatchable = Number(unref(snatchable))
		listData.value = []
		state.filtrate.pageNo = 1
		getList()
	}

	onMounted(async () => {
		// 获取位置信息
		uni.authorize({
			scope: 'scope.userLocation',
			success(res) {
				uni.getLocation({
					type: 'gcj02',
					success: async function (res) {
						const data = await addressResolution({ lat: res.latitude, lng: res.longitude });
						let result = data?.result;
						if (result) {
							uni.$u.vuex('vuex_location', {
								areaName: result?.ad_info?.city,
								cityName: result?.ad_info?.district,
								code: result?.ad_info?.adcode,
								provinceName: result?.ad_info?.province,
								name: result?.address,
							});
							uni.$u.vuex('vuex_current_position', result);
						}
					}, fail(err) {
						console.log(err, 'getLocation err');
					}
				});
			}, fail(err) {
				console.log(err, 'authorize err');
			}
		})

		businessCategory.value = await queryBusinessCategoryList()
		// listInit()
	})

	onShow(() => {
		listInit()
	})

	function listInit() {
		currentLocation.value = unref(proxy['vuex_current_position']).formatted_addresses.rough;
		state.filtrate.latitude = unref(proxy['vuex_current_position']).location.lat
		state.filtrate.longitude = unref(proxy['vuex_current_position']).location.lng
		state.filtrate.pageNo = 1
		listData.value = []
		getList()
	}

	async function getList() {
		const result = await queryUserActivityPage({ userId: unref(proxy['vuex_user']).id, ...state.filtrate })
		if (result.records.length !== 0) {
			listData.value = listData.value.concat(result.records)
			if (listData.value.length === result.total) {
				state.isLoadMore = true
				state.loadStatus = 'nomore'
			} else {
				state.isLoadMore = false
			}
		} else {
			state.isLoadMore = true
			state.loadStatus = 'nomore'
		}
	}

	//上拉触底函数
	onReachBottom(() => {
		if (!state.isLoadMore) {  //此处进行判断上锁，防止重复请求
			state.isLoadMore = true
			state.filtrate.pageNo += 1//页数加1
			getList()
		}
	})

	// 上拉刷新
	onPullDownRefresh(() => {
		//重新触发获取数据方法，刷新接口
		listData.value = []
		state.filtrate.pageNo = 1
		getList()
		//结束刷新
		uni.stopPullDownRefresh()
	})


	onPageScroll((e) => {
		let topHeight = e.scrollTop;
		scrollTop.value = topHeight;
		headerBgTop.value = topHeight > 100 ? 100 : topHeight / 1;
	})

	function handleShowScreen() {
		uni.pageScrollTo({
			scrollTop: 500,
			duration: 300
		})
		showScreen.value = true
	}

	async function handleAdditiveGroup() {
		let res = await queryXccQrCode({ areaCode: unref(proxy['vuex_location']).code, type: 1 })
		xccQrCodeImg.value = res[0].qrCodeUrl
		popAdditiveGroup.value = true
	}

	async function resettingDetermine() {
		checkPlatform.value = []
		checkCategory.value = []
		listData.value = []
		state.filtrate.pageNo = 1
		state.filtrate.shopType = []
		state.filtrate.platform = []
		await getList()
		showScreen.value = false
	}

	async function screenDetermine() {
		listData.value = []
		state.filtrate.pageNo = 1
		state.filtrate.shopType = unref(checkCategory).join()
		state.filtrate.platform = unref(checkPlatform).join()
		await getList()
		showScreen.value = false
	}

	function handleMapLocation() {
		uni.navigateTo({
			url: '/pages/mapLocation/mapLocation'
		});
		// uni.$on('update', function (data) {
		// 	listInit()
		// 	uni.$off('update')
		// })
	}

	function toOrderGrabbing(item) {
		uni.navigateTo({
			url: `/pages/orderGrabbing/orderGrabbing?id=${item.id}`
		});
		uni.setStorage({
			key: 'user_activity',
			data: JSON.stringify(item)
		})
		// uni.$on('update', function (data) {
		// 	listInit()
		// 	uni.$off('update')
		// })
	}

	function toBbeginnerTutorial() {
		uni.navigateTo({
			url: '/pages/beginnerTutorial/beginnerTutorial'
		});

	}

	function toSearchShop(value) {
		uni.navigateTo({
			url: `/pages/searchShop/searchShop?searchVal=${value}`
		});
	}

	// function toPageJump(type) {
	// 	var genderMap = {
	// 		'personalInformation': '/pages/personalInformation/personalInformation',
	// 		'inviteMerchant': '/pages/personalCenter/inviteMerchant',
	// 		'beginnerTutorial': '/pages/beginnerTutorial/beginnerTutorial'
	// 	};
	// 	uni.navigateTo({
	// 		url: genderMap[type]
	// 	});
	// }
</script>


<style lang="scss" scoped>
	.content {
		background: #F2F2F2;

		.home-header-top {
			font-size: 26rpx;
			font-weight: 400;
			color: #FFFFFF;
			width: calc(100% - 20rpx);
			position: fixed;
			z-index: 100;
			padding: 20rpx;
			transition: background-color 2s ease;
			// border: 1px solid #000;
			height: 150rpx;

			.map-text {
				margin-left: 5rpx;
			}
		}

		.home-header {
			padding-top: 200rpx;
			background: linear-gradient(180deg, #FF2A47 30%, #FE7E17 50%);

			.header-search {
				margin: 0 20rpx;
			}
		}

		.header-banner {
			height: 380rpx;
			width: 100%;
			background-color: #fff;

			.banner-img {
				width: 100%;
			}
		}

		.home-class {
			font-size: 24rpx;
			background-color: #fff;
			padding-bottom: 10rpx;

			.swiper ::v-deep .uni-swiper-dots-horizontal {
				bottom: 15rpx;
			}

			.swiper ::v-deep .uni-swiper-dot {
				width: 12rpx;
				height: 12rpx;
			}
		}

		/* wx */
		wx-swiper .wx-swiper-dots-horizontal {
			bottom: 15rpx;
		}

		wx-swiper .wx-swiper-dot {
			width: 12rpx;
			height: 12rpx;
		}



		.home-channel {
			background: linear-gradient(133deg, #FFA9A9 0%, #FA7777 99%);
			margin: 20rpx 20rpx 0 20rpx;
			padding: 5rpx 10rpx 10rpx 10rpx;
			border-radius: 12rpx;

			.channel-title {
				color: #fff;
				margin: 15rpx 0;

				.channel-title-text {
					font-size: 32rpx;
					font-weight: 500;
				}

				.channel-title-guide {
					font-size: 22rpx;
					font-weight: 400;
					// margin-top: 2rpx;
					padding-right: 10rpx;

					.guide-text {
						padding-left: 10rpx;
					}
				}
			}

			.channel-item-con {
				width: 50%;
				font-size: 28rpx;
				background: #fff;
				border-radius: 12rpx;
				margin: 10rpx;
				padding: 20rpx 10px;
				overflow: hidden;

				.con-main {
					width: 60%;

					.con-title {
						font-size: 28rpx;
						font-weight: 500;
						color: #333333;
						margin-bottom: 5rpx;
					}

					.con-r-btn {
						width: 70%;
						margin: 15rpx 15rpx 0 0;
					}

					.con-text {
						font-size: 18rpx;
						font-weight: 400;
						color: #505050;
						line-height: 30rpx;
						padding-right: 5rpx;
						position: relative;

						.text-color {
							color: #FF5046;
							font-weight: 500;
						}
					}
				}
			}

		}

		.shop-list-box {
			min-height: 1000rpx;
		}

		.screen-cont {
			position: relative;
			height: 90rpx;
			margin: 10rpx 20rpx 0 20rpx;
			justify-content: space-between;

			.screen-cont-right {
				font-size: 14px;
			}
		}

		.screen-other-btn {
			font-size: 14px;
			// border: 1px #DCDFE6 solid;
			background-color: rgb(245, 245, 245);
			padding: 5px 10px;
			height: 12px;
		}

		.screen-other-btn-active {
			color: #fff;
			border-color: rgb(249, 195, 108);
			background-color: rgb(249, 195, 108);
		}

		.screen-other-cont {
			width: calc(100% - 40rpx);
			position: absolute;
			background-color: #fff;
			padding: 20rpx;
			border-radius: 0rpx 0rpx 20rpx 20rpx;

			.other-cont-title {
				color: #000000;
				font-size: 28rpx;
				font-weight: 500;
				margin-bottom: 30rpx;
			}

			.other-cont-btn {
				margin: 20rpx 0;

				.btn {
					width: 48%;
				}
			}
		}

		.additive-group {
			padding: 30rpx;
			text-align: center;
			border-radius: 20rpx;

			.additive-group-title {
				font-size: 60rpx;
				font-weight: 700;
				color: #FF5046;
				margin: 25rpx 10rpx;
			}

			.additive-group-text {
				font-size: 42rpx;
				font-weight: 500;
				color: #333333;
			}
		}

	}
</style>